<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.jpg">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.jpg">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"matian.connorma.cn","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="项目中需要使用到缩略图功能，对比下来，使用nginx http_image_filter模块是最为快捷的方式，在此记录">
<meta property="og:type" content="article">
<meta property="og:title" content="nginx实现图片缩略图">
<meta property="og:url" content="http://matian.connorma.cn/a7ddaf0e.html">
<meta property="og:site_name" content="马天">
<meta property="og:description" content="项目中需要使用到缩略图功能，对比下来，使用nginx http_image_filter模块是最为快捷的方式，在此记录">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg">
<meta property="og:image" content="http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg?width=100">
<meta property="article:published_time" content="2022-06-18T11:59:57.000Z">
<meta property="article:modified_time" content="2024-04-26T11:48:37.396Z">
<meta property="article:author" content="马天">
<meta property="article:tag" content="nginx">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg">

<link rel="canonical" href="http://matian.connorma.cn/a7ddaf0e.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>nginx实现图片缩略图 | 马天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">马天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://matian.connorma.cn/a7ddaf0e.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="马天">
      <meta itemprop="description" content="程序猿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="马天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          nginx实现图片缩略图
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-06-18 19:59:57" itemprop="dateCreated datePublished" datetime="2022-06-18T19:59:57+08:00">2022-06-18</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/nginx/" itemprop="url" rel="index"><span itemprop="name">nginx</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>项目中需要使用到缩略图功能，对比下来，使用nginx http_image_filter模块是最为快捷的方式，在此记录</p>
<span id="more"></span>

<h2 id="nginx部署"><a href="#nginx部署" class="headerlink" title="nginx部署"></a>nginx部署</h2><p>image_filter模块依赖GD库，首先进行安装：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yum -y install gd-devel</span><br></pre></td></tr></table></figure>

<p>然后进行nginx部署，可参考<a target="_blank" rel="noopener" href="https://gitee.com/connormma/quick_launch_tools/blob/master/nginx/linux_amd64/">此脚本</a>，注意需要在编译时configure时使用’–with-http_image_filter_module’引入http_image_filter模块</p>
<h2 id="配置http-image-filter返回压缩图"><a href="#配置http-image-filter返回压缩图" class="headerlink" title="配置http_image_filter返回压缩图"></a>配置http_image_filter返回压缩图</h2><p>image_filter在location块内使用，支持以下参数：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">image_filter &lt;size&gt;; // 以json的方式输出图片格式信息</span><br><span class="line">image_filter rotate 90 | 180 | 270; // 图片逆时针旋转指定度数，该度数只能是90, 180, 270</span><br><span class="line">image_filter resize &lt;width&gt; &lt;height&gt;; // 缩小图片到指定的规格，如果想让一个维度缩放，另外一个维度等比例缩放，则另外维度参数值为&#x27;-&#x27;.如果配合rotate指令使用，那么执行顺序是先缩放，后旋转</span><br><span class="line">image_filter crop &lt;width&gt; &lt;height&gt;; // 按比例将图片缩小到较大的一边，并裁剪另一边多余的边缘</span><br><span class="line">image_filter test; // 确保图片格式为jpeg,gif,png,webp等格式，否则返回415错误（Unsupported Media Type）</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">image_filter_buffer 10M; // 默认1M。设置用于读取图片的缓冲区的最大大小。当超过指定大小时，服务器返回 415 错误状态码（不支持的媒体类型）</span><br><span class="line">image_filter_jpeg_quality 1~100; // 默认75。设置 JPEG 图片的转换质量。可接受的值范围在 1 到 100 之间。较小的值意味着较低的图片质量和较少的数据传输。最大的推荐值是 95</span><br><span class="line">image_filter_webp_quality 1~100; // 默认80。设置 WebP 图片的转换质量。可接受的值在 1 到 100 之间。较小的值意味着较低的图片质量和较少的数据传输</span><br><span class="line">image_filter_sharpen percent; // 默认0。增加最终图像的清晰度。锐度百分比可以超过 100。零值将禁用锐化</span><br><span class="line">image_filter_transparency on|off; // 默认on。定义在使用调色板指定的颜色转换 GIF 图像或 PNG 图像时是否保留透明度。透明度的丧失使图像的质量更好的。PNG 中的 alpha 通道透明度始终保留</span><br><span class="line">image_filter_interlace on|off; // 默认off。如果启用此选项，图片最后将被逐行扫描。对于 JPEG，图片最终将采用逐行JPEG格式，即从上到下扫描图片，显示时一行一行加载显示出来</span><br></pre></td></tr></table></figure>

<p>以nginx代理静态文件为例，对图片类型（jpg|jpeg|gif|png）的请求，如果携带了width&#x2F;height参数，那么将按照入参进行压缩处理</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"> # 缩略图</span><br><span class="line"> location ~* /blogexamplebucket/(.+)\.(jpg|jpeg|gif|png) &#123;</span><br><span class="line">   # 设置变量width默认为&#x27;-&#x27;</span><br><span class="line">   set $width -;</span><br><span class="line">   # 读取参数携带的width值</span><br><span class="line">   if ($arg_width) &#123;</span><br><span class="line">     set $width $arg_width;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   # 希望等比例缩放，这里只使用width参数，将宽度缩小到width，高度将等比例缩小</span><br><span class="line">   image_filter resize $width -;</span><br><span class="line">   image_filter_jpeg_quality 75;</span><br><span class="line">   # 图片缓存区最大20M</span><br><span class="line">   image_filter_buffer 20M;</span><br><span class="line">   </span><br><span class="line">   # 代理服务器文件</span><br><span class="line">   # 按照location的模式匹配，$1.$2 为请求的文件名</span><br><span class="line">   proxy_pass http://your-file-server/blogexamplebucket/$1.$2;</span><br><span class="line">   # 指定缓存expires时长永不过期</span><br><span class="line">   expires                 max;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"># 代理 oss blogexamplebucket 下文件</span><br><span class="line">location /blogexamplebucket/ &#123;</span><br><span class="line">   # 代理服务器文件</span><br><span class="line">   proxy_pass http://your-file-server;</span><br><span class="line">  expires                 max;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>如果原始图片url为：<a target="_blank" rel="noopener" href="http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg">http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg</a></p>
<p><img src="http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg" alt="原始图片" title="原始图片"></p>
<p>希望使用缩略图，那么可以添加width参数：<a target="_blank" rel="noopener" href="http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg?width=100">http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg?width=100</a></p>
<p><img src="http://blog-oss.connorma.cn/blogexamplebucket/hutao.jpg?width=100" alt="缩略图" title="缩略图"></p>
<h2 id="缩略图缓存"><a href="#缩略图缓存" class="headerlink" title="缩略图缓存"></a>缩略图缓存</h2><p>在以上示例中代理静态文件时设置了expires为max，使浏览器使用缓存，但是nginx侧性能考虑，每次请求时处理图片，将会带来一定的性能压力——jmeter跑一下请求缩略图，轻松就能把nginx机器的CPU打满</p>
<p>因此，考虑nginx使用proxy_store为缩略图添加磁盘缓存，一方面减少了图片处理的操作，另一方面通过nginx本地缓存加快客户端的响应速度</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"># 缩略图</span><br><span class="line">location ~* /blogexamplebucket/(.+)\.(jpg|jpeg|gif|png) &#123;</span><br><span class="line">  # 设置变量width默认为&#x27;-&#x27;</span><br><span class="line">  set $width -;</span><br><span class="line">  # 读取参数携带的width值</span><br><span class="line">  if ($arg_width) &#123;</span><br><span class="line">    set $width $arg_width;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  # 希望等比例缩放，这里只使用width参数，将宽度缩小到width，高度将等比例缩小</span><br><span class="line">  image_filter resize $width -;</span><br><span class="line">  image_filter_jpeg_quality 75;</span><br><span class="line">  # 图片缓存区最大20M</span><br><span class="line">  image_filter_buffer 20M;</span><br><span class="line">  </span><br><span class="line">  # 代理服务器文件</span><br><span class="line">  # 按照location的模式匹配，$1.$2 为请求的文件名</span><br><span class="line">  proxy_pass http://your-file-server/blogexamplebucket/$1.$2;</span><br><span class="line">  # 指定缓存expires时长永不过期</span><br><span class="line">  expires                 max;</span><br><span class="line">  </span><br><span class="line">  # 开启本地磁盘缓存</span><br><span class="line">  proxy_store          /data/nginx_cache/images/resize/$1_$2_$width;</span><br><span class="line">  # 缓存路径读写权限</span><br><span class="line">  proxy_store_access   user:rw  group:rw  all:r;</span><br><span class="line">  # 缓存文件路径</span><br><span class="line">  proxy_temp_path      /data/nginx_cache/images/resize;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>需要注意，在使用磁盘缓存时，nginx会将文件首先写入临时目录proxy_temp_path下，然后移动到proxy_store指定的路径下(如果未指定，那么会保存到root或alias指定的路径下)，因此为了减少IO压力，建议proxy_temp_path和proxy_temp_path使用同一FS下目录</p>
<p>proxy_store使用磁盘缓存文件，但是并不原生的支持缓存过期清理，缓存文件将占用大量磁盘空间；proxy_cache的缓存功能在这方面更完备，但是只支持内存的写入，不适合此类数量多、体积相对大的静态文件的情况。如何处理？可以集成lua模块（或使用openResty）嵌入脚本来清理文件，或者通过服务器内的crontab任务释放缓存空间等</p>
<blockquote>
<p>不难想到，proxy_store按照示例的配置，就实现了回源。如果你在多地有机器部署了nginx，通过proxy_store，配合清理缓存文件的策略，就能实现一个基本的CDN</p>
</blockquote>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/nginx/" rel="tag"># nginx</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/c7e143e.html" rel="prev" title="看Spring事务机制的实现">
      <i class="fa fa-chevron-left"></i> 看Spring事务机制的实现
    </a></div>
      <div class="post-nav-item">
    <a href="/81ee92e1.html" rel="next" title="mysql8 with使用与场景示例：用户邀请记录查询">
      mysql8 with使用与场景示例：用户邀请记录查询 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#nginx%E9%83%A8%E7%BD%B2"><span class="nav-number">1.</span> <span class="nav-text">nginx部署</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%85%8D%E7%BD%AEhttp-image-filter%E8%BF%94%E5%9B%9E%E5%8E%8B%E7%BC%A9%E5%9B%BE"><span class="nav-number">2.</span> <span class="nav-text">配置http_image_filter返回压缩图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BC%A9%E7%95%A5%E5%9B%BE%E7%BC%93%E5%AD%98"><span class="nav-number">3.</span> <span class="nav-text">缩略图缓存</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">马天</p>
  <div class="site-description" itemprop="description">程序猿</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">41</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">25</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/matian2014" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;matian2014" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:matian1103@qq.com" title="E-Mail → mailto:matian1103@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">陕ICP备2023001563号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">马天</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
